package domein;

import java.sql.SQLException;
import java.util.Map;
import javax.swing.tree.DefaultMutableTreeNode;

import persistentie.MapperFactory;

public class WereldMapper {
	

	private Wereld wereld;
	private DomeinController domeinController;
	
	public WereldMapper(DomeinController domeinController)
	{
		this.domeinController = domeinController;
	}

	public Wereld getWereldMap() throws IllegalStateException, SQLException, ClassNotFoundException
	{
		wereld = new Wereld();
		Map<String, Continent> mapContinenten = MapperFactory.getInstance().getMapper(Continent.class).read();
		wereld.setContinenten(mapContinenten);
		
		for(Map.Entry<String, Continent> entryContinent : wereld.getContinenten().entrySet()) 
		{
			Continent continent = entryContinent.getValue();
		    
		    Map<String, Land> mapLanden = MapperFactory.getInstance().getMapper(Land.class).read(continent.getIDContinent());
		    continent.setLanden(mapLanden);
		    
		    for(Map.Entry<String, Land> entryLand : continent.getLanden().entrySet())
		    {
		    	Land land = entryLand.getValue();
		    	
		    	 Map<String, Locatie> mapLocaties = MapperFactory.getInstance().getMapper(Locatie.class).read(land.getCodeLand());
		    	land.setLocaties(mapLocaties);
		    }
		    
		}
		
		domeinController.setWereld(wereld);
		return wereld;
	}
	
	
	public DefaultMutableTreeNode makeTreeModel() throws IllegalStateException, SQLException, ClassNotFoundException 
	{		
		
		wereld = getWereldMap();
		
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode( "Wereld" );
		
		for(Map.Entry<String, Continent> entry : wereld.getContinenten().entrySet()) 
		{
			Continent continent = entry.getValue();
			DefaultMutableTreeNode node = new DefaultMutableTreeNode( continent.getNaamContinent() );
		    rootNode.add( node );
		    
		    for(Map.Entry<String, Land> entry2 : wereld.getContinenten().get(continent.getNaamContinent()).getLanden().entrySet())
		    {
		    	Land land = entry2.getValue();
		    	DefaultMutableTreeNode nodeLocatie = new DefaultMutableTreeNode( land.getNaamLand() );
		    	node.add( nodeLocatie );
		    	
		    	for(Map.Entry<String, Locatie> entryLocatie : wereld.getContinenten().get(continent.getNaamContinent()).getLanden().get(land.getNaamLand()).getLocaties().entrySet())
		    	{
		    		Locatie locatie = entryLocatie.getValue();
		    		nodeLocatie.add( new DefaultMutableTreeNode(locatie.getNaamLocatie()));
		    	}
		    }
		}
		
		return rootNode;
	}
}
